var express = require("express");
var app = express(); //引入express库
var http = require("http").Server(app); //将express注册到http中
var io = require("socket.io")(http);

app.use(express.json());

app.use("/public", express.static("public"));
//当访问根目录时，返回index.html
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

app.get("/favicon.ico", function (req, res) {
    res.sendFile(__dirname + "/Chat.png");
});

app.post("/login", function (req, res) {
    var uselist = {
        管理员: "789456",
        senk: "789456",
        senx: "789456",
    };
    console.log(req.body);
    if (uselist[req.body.use] == req.body.pwd) {
        res.send("login succeed");
    } else {
        res.send("password erro");
    }
});

var usocket = []; //全局变量
io.on("connection", function (socket) {
    console.log("a user connected");

    //监听join事件
    socket.once("join", function (usename) {
        usocket[usename] = socket;
        io.emit("join", usename); //服务器通过广播将新用户发送给全体群聊成员
        console.log(usename + " joined");
    });

    socket.on("message", function (msg) {
        io.emit("message", msg); //将新消息广播出去
    });
});
//监听端口号
http.listen(8080, "0.0.0.0", () => {
    // 控制台会输出以下信息
    console.log("Server running at http://127.0.0.1:8080/");
});
